package com.aliyun.tools.importdialog;



import java.awt.event.TextEvent;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.gnome.gdk.Cursor;
import org.gnome.glade.Glade;
import org.gnome.glade.XML;
import org.gnome.glib.Signal;
import org.gnome.gtk.Button;
import org.gnome.gtk.ButtonsType;
import org.gnome.gtk.Entry;
import org.gnome.gtk.Fixed;

import org.gnome.gtk.Editable;
import org.gnome.gtk.EntryCompletion;
import org.gnome.gtk.Label;
import org.gnome.gtk.MessageDialog;
import org.gnome.gtk.MessageType;
import org.gnome.gtk.Notebook;
import org.gnome.gtk.PolicyType;
import org.gnome.gtk.ResponseType;
import org.gnome.gtk.ScrolledWindow;
import org.gnome.gtk.TextBuffer;
import org.gnome.gtk.TextView;
import org.gnome.gtk.TreeIter;
import org.gnome.gtk.TreeModel;
import org.gnome.gtk.VBox;
import org.gnome.gtk.Widget;
import org.gnome.gtk.Window;
import org.gnome.gtk.Editable.CHANGED;

import com.aliyun.tools.controldatarunnable.createTableRunnable;
import com.mine.control.ControlTable;
import com.mine.main.DiffOfReport;


public class ImportCategoryChooser{
	Window parentWin;
	int selfWidth;
	int selfHeight;
	Date currentDate;
	int pageCount = 0;
	
	createTableRunnable runnableCreateTable;
	
	public boolean importCategoryChooserShowed = false;
	private boolean isFolder = false;
	
	/**
	 * 将从glade文件中获得窗口信息，保存到字段中，进行相关操作，来改变窗口显示情况。
	 * @author jian.hj
	 */
	XML winImportCategoryChooser;
	static Window importCategoryChooserWin;
	
	static Button btnChoosePath;
	static Button btnOk;
	static Button btnQuit;
	static Button btnHarmony;
	static Button btnJck_Api;
	static Button btnJck_Lang;
	static Button btnJni;
	static Button btnStress;
		
	static Entry entryVersion;
	static Entry entryDate;
	static Entry entryCategory;
	static Entry entryPath;
	
	ImportFileChooser filechooser;
	/**
	 * 初始化导入窗口填写信息对话框
	 * 
	 * @param winMain
	 * @param width
	 * @param height
	 * @throws FileNotFoundException
	 * @author jian.hj
	 */
	public ImportCategoryChooser(Window winMain, int width, int height) throws FileNotFoundException{
		this.parentWin = winMain;
		this.selfWidth = width;
		this.selfHeight = height;
		currentDate = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		/**
		 * 从glade文件中读取窗口配置信息。
		 * @author jian.hj
		 */
		winImportCategoryChooser = Glade.parse("resources/tool_import_dialog_winMain.glade", "tool_import_dialog_winMain");
		importCategoryChooserWin = (Window) winImportCategoryChooser.getWidget("tool_import_dialog_winMain");
		
		entryVersion = (Entry)winImportCategoryChooser.getWidget("entry_version");
		entryDate = (Entry )winImportCategoryChooser.getWidget("entry_date");
		entryDate.setText(dateFormat.format(currentDate));
		entryCategory = (Entry )winImportCategoryChooser.getWidget("entry_category");
		entryPath = (Entry )winImportCategoryChooser.getWidget("entry_path");
		
		
		btnHarmony = (Button) winImportCategoryChooser.getWidget("btn_harmony");
		btnJni = (Button) winImportCategoryChooser.getWidget("btn_jni");
		btnJck_Api = (Button) winImportCategoryChooser.getWidget("btn_jckapi");
		btnJck_Lang = (Button) winImportCategoryChooser.getWidget("btn_jcklang");
		btnStress = (Button) winImportCategoryChooser.getWidget("btn_stress");
		
		btnOk = (Button) winImportCategoryChooser.getWidget("btn_ok");
		btnQuit = (Button) winImportCategoryChooser.getWidget("btn_quit");
		btnChoosePath = (Button) winImportCategoryChooser.getWidget("btn_path");

		/**
		 * Harmony 按钮
		 * @author jian.hj
		 */
		btnHarmony.connect(
				new Button.Clicked() {
						public void onClicked(Button paramButton) {
						// TODO Auto-generated method stub
							entryCategory.setText("Harmony");
							isFolder = false;
					}
				});
		/**
		 * 
		 * JNI 按钮
		 * @author jian.hj
		 */
		btnJni.connect(
				new Button.Clicked() {
						public void onClicked(Button paramButton) {
						// TODO Auto-generated method stub
							entryCategory.setText("JNI");
							isFolder = false;
					}
				});
		
		/**
		 *	JCK Api 按钮
		 *	@author jian.hj 
		 */
		btnJck_Api.connect(
				new Button.Clicked() {
						public void onClicked(Button paramButton) {
						// TODO Auto-generated method stub
							entryCategory.setText("JCK_API");
							isFolder = false;
					}
				});
		
		/**
		 *	JCK Lang 按钮
		 *	@author jian.hj 
		 */
		btnJck_Lang.connect(
				new Button.Clicked() {
						public void onClicked(Button paramButton) {
						// TODO Auto-generated method stub
							entryCategory.setText("JCK_LANG");
							isFolder = false;
					}
				});
		
		/**
		 * Stress 按钮
		 * @author jian.hj
		 */
		btnStress.connect(
				new Button.Clicked() {
						public void onClicked(Button paramButton) {
						// TODO Auto-generated method stub
							entryCategory.setText("Stress");
							isFolder = true;
					}
				});
		
		/**
		 * 选择文件或文件夹 按钮
		 * @author jian.hj
		 */
		btnChoosePath.connect(
				new Button.Clicked() {
						public void onClicked(Button paramButton) {
						// TODO Auto-generated method stub
						filechooser = new ImportFileChooser(parentWin, selfHeight, selfHeight, isFolder);					
						ResponseType choice = filechooser.Run();
						if(choice == ResponseType.CANCEL){
							if(entryPath.getText().length() == 0)
								filechooser.setFilePath("");
							else
								filechooser.setFilePath(entryPath.getText());
						}
						if(choice == ResponseType.OK){
							entryPath.setText(filechooser.getFilePath());
						}
						filechooser.hide();			
					}
				});
		
		/**
		 *	退出按钮
		 *	@author jian.hj 
		 */
		btnQuit.connect(
				new Button.Clicked() {
						public void onClicked(Button paramButton) {
						// TODO Auto-generated method stub
							importCategoryChooserWin.hide();
					}
				});
		
		/**
		 * 确定 按钮
		 * @author jian.hj
		 */
		btnOk.connect(
				new Button.Clicked() {
						public void onClicked(Button paramButton) {
						// TODO Auto-generated method stub
							String category = getCategory();
//							String date = getDate();
							String version = getVersion();
							String path = getPath();
							
							if(entryCategory.getText().length() != 0 && entryVersion.getText().length() != 0 && entryPath.getText().length() != 0 &&
									!(entryVersion.getText().contains("."))){
								
								MessageDialog messageDialog = new MessageDialog(importCategoryChooserWin, true, MessageType.QUESTION, ButtonsType.YES_NO, "是否继续导入其他文件？");
								ResponseType choice = messageDialog.run();
								
								if(choice == ResponseType.YES){
									//doing nothing
								
								}else if(choice == ResponseType.NO){
									importCategoryChooserWin.hide();
									//need doing more something
								}
								
								addCategoryRet(parentWin, category, version, path);
								messageDialog.hide();
								entryCategory.setText("");
								entryPath.setText("");
								
							}else{
								
								MessageDialog messageDialog = new MessageDialog(importCategoryChooserWin, true, MessageType.WARNING, ButtonsType.CLOSE, "请先选择导入文件的测试类型、版本号、文件路径！");
								messageDialog.run();
								messageDialog.hide();
							}
					}

				});
	}
	
	/**
	 * 	显示 导入窗口
	 * 	@author jian.hj
	 */
	public void showAll(){
		importCategoryChooserWin.showAll();
		importCategoryChooserShowed = true;
	}
	
	/**
	 *	隐藏 导入窗口
	 *	@author jian.hj 
	 */
	public void hide(){
		importCategoryChooserWin.hide();
		importCategoryChooserShowed = false;
	}
		
	public String getCategory(){
		return entryCategory.getText();
	}
	
	public String getDate(){
		return entryDate.getText();
	}
	
	public String getPath(){
		return entryPath.getText();
	}
	
	public String getVersion(){
		return entryVersion.getText();
	}
	
	/**
	 * 在主窗口增加测试类文件比对结果
	 * @param parentWin
	 * @param category
	 * @param date
	 * @param inFilePath
	 * @param version
	 */
	public void addCategoryRet(Window parentWin, String category, String version, String path){
		String outFilePath;
		String buffer = null;
		Widget widget = getParentWinChildren(parentWin);
		try {
			insertDB(version, category, path);
			outFilePath = compareAndReturnOutFilePath(version, category, path);
			buffer = readCompareRet(outFilePath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		changedWin(widget, category, buffer);
	}
		
	public Widget getParentWinChildren(Window parentWin){
		VBox children = (VBox)parentWin.getChildren()[0];
		Widget[] sonWidgets = children.getChildren();
		Widget grandsonWidget = null;
		for(int i = 0; i < sonWidgets.length; i++){
			Fixed oldFixed = (Fixed) sonWidgets[i];
			Widget[] grandsonWidgets = oldFixed.getChildren();
			for(int j = 0; j<grandsonWidgets.length; j++){
				if(grandsonWidgets[j].getClass().getName().equals("org.gnome.gtk.Notebook")){
					 grandsonWidget = grandsonWidgets[j];
					break;
				}
			}
		}
		return grandsonWidget;
	}

	public void changedWin(Widget widget, String category, String insertbuffer){
		
		Notebook changeNoteBook = (Notebook)widget;
		pageCount = changeNoteBook.getPageCount();
		
		if(pageCount == 1){
			ScrolledWindow scrolledWindow = (ScrolledWindow) changeNoteBook.getChildren()[0];
			TextView textView = (TextView) scrolledWindow.getChildren()[0];
			TextBuffer buffer = textView.getBuffer();
			if(buffer.getCharCount() == 0){
				changeNoteBook.removePage(0);
			}
		}
		TextBuffer textBuffer = new TextBuffer();
		textBuffer.setText(insertbuffer);
		TextView textViewNew = new TextView(textBuffer);
		textViewNew.setEditable(false);
		textViewNew.setCursorVisible(false);
		textViewNew.setBorderWidth(5);
		ScrolledWindow scrolledWindowNew = new ScrolledWindow();
		scrolledWindowNew.setPolicy(PolicyType.AUTOMATIC, PolicyType.ALWAYS);			
		scrolledWindowNew.add(textViewNew);
		Label label = new Label(category);
		changeNoteBook.appendPage(scrolledWindowNew, label); 
		changeNoteBook.getParent().showAll();
	}
	
	public void insertDB(String version, String category, String inFilePath) throws Exception{

		String tableName = version +"_"+ category;
		if(!ControlTable.searchTable(tableName))
			ControlTable.createTable(tableName);
		System.out.println("begin importing.......");
		ControlTable.inputTargerTable(inFilePath, tableName, category);		
		System.out.println("end import.....");
	}
	
	public String compareAndReturnOutFilePath(String version, String category,String inFilePath) throws SQLException, Exception{
		String outFilePath = null;
		String comparedTableName = null;
		
		if (("Harmony").equals(category)) {
			//
			outFilePath = "harmony_diff.txt";
			comparedTableName = "";
		}else if(("JCK_API").equals(category)) {
			outFilePath = "jckapi_diff.txt";
			comparedTableName="dalvik_jck_api_report";
		} else if (("JCK_LANG").equals(category)) {
			outFilePath = "jcklang_diff.txt";
			comparedTableName="dalvik_jck_lang_report";
		} else if (("JNI").equals(category)) {
			//
			outFilePath = "jni_diff.txt";
			comparedTableName="";
		} else if(("STRESS").equals(category)){
			outFilePath = "stress_diff.txt";
			comparedTableName="dalvik_stress_report";
		}
		System.out.println("begin comparing.......");
		DiffOfReport.diffReport(inFilePath, comparedTableName, outFilePath, category);
		System.out.println("end compare.......");
		return outFilePath;
	}
	
	public String readCompareRet(String outFilePath) throws IOException{
		FileReader fileReader = new FileReader(outFilePath);
		BufferedReader bufferReader = new BufferedReader(fileReader);
		String line = null;
		String buffer = "";
		while((line = bufferReader.readLine())!= null){
			buffer+=line+"\n";
		}
		return buffer;
	}

}
